package com.ee.chat.api.task;

import com.ee.chat.api.common.CommonService;
import com.ee.chat.common.dao.DataAnalysisLogMapper;
import com.ee.chat.common.entity.DataAnalysisLog;
import com.ndhutu.ee.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author AppiJ
 * @Date 2020/10/13 14:51
 */
@Component
public class StatisticTask {
    private Logger log = LoggerFactory.getLogger(StatisticTask.class);

    @Resource
    DataAnalysisLogMapper dataAnalysisLogMapper;
    @Resource
    CommonService commonService;

    /**
     * 数据分析统计，每一个小时，整点统计
     * @Author AppiJ
     * @Date 2020/10/13 14:52
     * @param
     * @return
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void dataAnalysisStatistic() throws Exception{
        if(!commonService.getIpStatus()){
            return;
        }

        log.info("数据分析定时统计开始");
        Date date = new Date();
        String beginTime = DateUtil.getFullTime(date, -1);
        String endTime = DateUtil.getFullTime(date, 0);
        DataAnalysisLog registerRecharge = dataAnalysisLogMapper.getDataAnalysisStatistic(beginTime, endTime);
        if(registerRecharge == null){
            registerRecharge = new DataAnalysisLog(0, 0, 0,
                    0, 0, DateUtil.parse(endTime));
        }
        dataAnalysisLogMapper.insert(registerRecharge);
        log.info("数据分析定时统计结束");
    }

    @Transactional(rollbackFor = Exception.class)
    public void initDataAnalysis() throws Exception{

        log.info("------------------数据分析初始化 开始---------------");

        //获取第一条统计记录时间
        String dateTime = dataAnalysisLogMapper.getBeginTime();
        String beginTime = DateUtil.getFullTime(DateUtil.parse(dateTime), 0);
        String endTime = DateUtil.getFullTime(DateUtil.parse(dateTime), 1);
        while (DateUtil.parse(endTime).getTime() < (new Date()).getTime()) {
            DataAnalysisLog registerRecharge = dataAnalysisLogMapper.getDataAnalysisStatistic(beginTime, endTime);
            if(registerRecharge == null){
                registerRecharge = new DataAnalysisLog(0, 0, 0,
                        0, 0, DateUtil.parse(endTime));
            }
            dataAnalysisLogMapper.insert(registerRecharge);

            beginTime = endTime;
            endTime = DateUtil.getFullTime(DateUtil.parse(endTime), 1);
        }

        log.info("------------------数据分析初始化 结束---------------");
    }
}
